<template>
    <!-- <div>
      <p>note</p>
    </div> -->
    <van-pull-refresh
      v-model="freshLoading"
      success-text="刷新成功"
      head-height="100"
      @refresh="onRefresh">


    <div style=" background-color: #fff;height: 14vw;">
      <span class="n-title" v-if="store.loverInfo!=null">{{info}}</span>

      <span class="n-addnote">
        <van-icon name="add" size="6vw" color="#5dacdd" @click="onAddNote"/>
      </span>
    </div>

    <div  class="n-notetitle" style="color:#62c889;">
      <van-icon name="add" size="5vw" color="#62c889" />
      <span style="margin-top: 3vw;">  ---新的待办--------------------</span>
    </div>

    <div class="n-newNote" v-for="(note,index) in newNotes" :key="note.noteId">
      
      <div class="n-noteTop">
      </div>
      <Transition name="slide-fade"  v-show="note.isShowItem"  v-for="item in note.noteItems" :key="item.itemId">
        <div class="n-item" >
            <div style="width: 80vw;">{{item.itemContent}}</div>
            <div style="width:8vw;padding-left:2vw;box-sizing: border-box;">
              <van-icon name="clear" size="6vw" @click="onDelete(item.itemId)" />
            </div>
        </div>
      </Transition>
      <Transition name="slide-fade">
        <div class="n-item" v-show="note.isShowInput">
              <div style="width: 80vw;">
                <van-cell-group inset>
                  <van-field v-model="newNoteItem" rows="1" autosize type="textarea" placeholder="写下想一起做的事吧!"
                  />
                </van-cell-group>
              </div>
              <div style="width:8vw;padding-left:2vw;box-sizing: border-box;">
                <van-icon name="checked" size="6vw" color="#62c889" @click="onAddNoteItem(note.noteId)"/>
              </div>
        </div>
      </Transition>
      <div class="n-noteBottom"> 
        <div>
            <van-button color="#f9cdd4" size="small"  @click="onStart(note.noteId, index)">开 始</van-button>
            <van-button color="#fc4747" size="small"  @click="onDeleteNote(note.noteId)" style="margin-left: 4vw;">删 除</van-button>
        </div>
        <div style="width:18vw;padding-left:2vw;box-sizing: border-box;">
          <van-icon name="add-o" size="6vw" @click="onShowInput(index)"/>
          <span>&nbsp;&nbsp;&nbsp;</span>
          <van-icon :name="arrow(note.isShowItem)" size="6vw" @click="onShowItem(0,index)"/>
        </div>
      </div>
    </div>
    
    <div  class="n-notetitle" style="color:#dd785d;">
      <van-icon name="add" size="5vw" color="#dd785d" />
      <span style="margin-top: 3vw;">  ---进行中的待办--------------</span>
    </div>
    
    <div class="n-newNote" v-for="(note,index) in nowNotes" :key="note.noteId">
      <div class="n-noteTop">
      </div>
    <Transition name="slide-fade"  v-show="note.isShowItem"  v-for="item in note.noteItems" :key="item.itemId">
      <div class="n-item" >
          <div style="width: 80vw;">
            <van-checkbox  v-model="item.itemState" checked-color="#dd785d">{{item.itemContent}}</van-checkbox>
          </div>
          <!-- <div style="width:8vw;padding-left:2vw;box-sizing: border-box;">
            <van-icon name="clear" size="6vw" @click="onDelete(item.itemId)"/>
          </div> -->
      </div>
    </Transition>
      <div class="n-noteBottom"> 
        <van-button color="#f9cdd4" size="small"  @click="onFinish(note.noteId, index)">确认结束</van-button>
        <div style="width:12vw;padding-left:2vw;box-sizing: border-box;">
          <span>&nbsp;&nbsp;&nbsp;</span>
          <van-icon :name="arrow(note.isShowItem)" size="6vw" @click="onShowItem(1,index)"/>
        </div>
      </div>
    </div>

    <div  class="n-notetitle" style="color:#d8ba92;">
      <van-icon name="add" size="5vw" color="#d8ba92" />
      <span style="margin-top: 3vw;">  ---历史待办--------------------</span>
    </div>

    <div class="n-newNote" v-for="(note,index) in hisNotes" :key="note.noteId">
      <div class="n-noteTop">
      </div>
      <Transition name="slide-fade"  v-show="note.isShowItem"  v-for="item in note.noteItems" :key="item.itemId">
        <div class="n-item" >
            <div style="width: 80vw;">{{item.itemContent}}</div>
            <div style="width:8vw;padding-left:2vw;box-sizing: border-box;">
              <van-icon v-if="item.itemState==1" name="success" color="#62c889"/>
            </div>
        </div>
      </Transition>
      <div class="n-noteBottom"> 
        <div>
          <van-button color="#f9cdd4" size="small"  :disabled="(note.shareState==1)" @click="onShare(note.noteId)" style="margin-right: 2vw;">分 享</van-button>
          <van-button color="#f9cdd4" size="small"  @click="onUpUnfinished(note.noteId,index)">重置未完成项</van-button>
          <van-button color="#fc4747" size="small"  @click="onDeleteNote(note.noteId)" style="margin-left: 4vw;">删 除</van-button>
        </div>
        <div style="width:12vw;padding-left:2vw;box-sizing: border-box;">
          <!-- <van-icon name="add-o" size="6vw" @click="onShowInput"/> -->
          <span>&nbsp;&nbsp;&nbsp;</span>
          <van-icon :name="arrow(note.isShowItem)" size="6vw" @click="onShowItem(2,index)"/>
        </div>
      </div>
    </div>
  </van-pull-refresh>
</template>
  
  <script>
  import axios from "axios"
  import {store} from '../utils/store.js'
  import { showToast,showSuccessToast, showFailToast, showConfirmDialog } from 'vant';
  import {getTimeSub} from "../utils/time.js"
  
  export default {
    name: 'HomeView',
    activated(){
      store.active="note"
      console.log(store.note)
      if(!store.queryFlag){
        this.$router.replace("/home/diary")
      }else{
        if(store.loverInfo!=null&&!store.note){
          this.getAllNotes(store.loverInfo.loverId)
          store.note=true
        }
      }
    },
    // mounted(){
    //   store.active="note"
    //   if(!store.queryFlag){
    //     this.$router.replace("/home/diary")
    //     store.active="diary"
    //   }else{
    //     if(store.loverInfo!=null&&!store.note){
    //       this.getAllNotes(store.loverInfo.loverId)
    //       store.note=true
    //     }
    //   }
    // },
    data(){
      return{
        store,
        freshLoading: false,
        // seperateTime: 10,  //顶部显示的信息
        newNoteItem: "",       //绑定的输入框内容    
        arrowstyle: ["arrow-up","arrow-down"],
        //对于添加的数据,需要设置几个属性. 
        //1. 针对note要加一个isShowInput,默认为false,点击加号时可以使出现
        //2. 针对note要加一个isShowItem, 默认为true,点击加号收折时可以隐藏
        //noteId,loverId,noteState(0未开始,1进行中,2已完成),list(noteItem),shareTime
        //itemId,noteId,itemContent,itemState(0未完成,1已完成)
        newNotes:[],           
        nowNotes:[],
        hisNotes:[],

      }
    },
    computed:{
      info(){
        if(this.nowNotes.length>0){
          return "请享受你们的时光!"
        }else{
          if(store.loverInfo.lastTime==""){return "情侣待办"}
          var seperateTime = getTimeSub(Number(store.loverInfo.lastTime), Date.now())
          return "已分开"+seperateTime
        }
      },
    },
    methods:{
      onRefresh(){
        axios.get('/api/Note/getAllNotes', {
            params:{
              loverId: store.user.loverId
            }
            })
            .then((res)=>{
              var data = res.data.data
              console.log(data)
              if(data==""){return}
              this.newNotes=[]
              this.nowNotes=[]
              this.hisNotes=[]
              data.forEach(element => {
                 switch (element.noteState) {
                   case 0:
                     element.isShowInput = false
                     element.isShowItem = true
                     this.newNotes.push(element)
                     break;
                   case 1:
                     element.isShowItem = true
                     this.nowNotes.push(element)
                     break;
                   case 2:
                     element.isShowItem = true
                     this.hisNotes.push(element)
                     break;
                   default:
                     break;
                 }
              })
              this.freshLoading=false
            })
            .catch(function (error) {
              console.log(error);
              showFailToast("刷新失败！")
              this.freshLoading=false
            })  
        
      },
      getAllNotes(){
        this.newNotes=[]
        this.nowNotes=[]
        this.hisNotes=[]
        axios.get('/api/Note/getAllNotes', {
            params:{
              loverId: store.user.loverId
            }
            })
            .then((res)=>{
              var data = res.data.data
              console.log(data)
              data.forEach(element => {
                //  console.log(element)
                 switch (element.noteState) {
                   case 0:
                     element.isShowInput = false
                     element.isShowItem = true
                     this.newNotes.push(element)
                     break;
                   case 1:
                     element.isShowItem = true
                     this.nowNotes.push(element)
                     break;
                   case 2:
                     element.isShowItem = true
                     this.hisNotes.push(element)
                     break;
                   default:
                     break;
                 }
              });
            })
            .catch(function (error) {
              console.log(error);
            })  
      },
      onAddNote(){
        //axios请求，携带情侣id
        axios.get('/api/Note/addNote', {
              params:{
                loverId:store.loverInfo.loverId
              }
            }).then((res)=>{
              this.onRefresh()
              //返回那个新的note
              //然后用unshift()方法添加到newNote的头部
              showSuccessToast(res.data.message);
            }).catch(function (error) {
                console.log(error);
            }) 
      },
      onAddNoteItem(id){
        if(this.newNoteItem==""){
          showToast("请输入内容")
          return
        }
        axios.get('/api/Note/addNoteItem', {
              params:{
                noteId:id,
                itemContent:this.newNoteItem
              }
            }).then((res)=>{
              console.log(res.data)
              this.newNoteItem=""
              this.onRefresh()
              //返回新的item
              //然后用unshift()方法添加到Note的尾部
            }).catch(function (error) {
                console.log(error);
            }) 
          
      },
      onDelete(id){
        showConfirmDialog({
          message:
            '确认删除？',
        })
        .then(() => {
          axios.get('/api/Note/deleteNoteItem', {
              params:{
                itemId: id
              }
            }).then((res)=>{
              console.log(res.data)
              this.onRefresh()
            }).catch(function (error) {
                console.log(error);
            }) 
        })
        .catch(() => {
            // on cancel
        });
      },
      onStart(id,index){
        if(this.newNotes[index].noteItems.length==0){
          showToast("还未添加待办项")
          return
        }
        axios.get('/api/Note/startNote', {
              params:{noteId:id}
            }).then((res)=>{
              console.log(res.data)
              this.onRefresh()
              //这个时候必须刷新allnotes
            }).catch(function (error) {console.log(error);}) 
        //开始待办
      },
      onFinish(id,index){
        showConfirmDialog({
          message:
            '确认结束？',
        })
        .then(() => {
          // states = []
          // this.nowNotes[index].noteItems.forEach(element => {
          //   states.push(element.itemState)
          // });
          // console.log(states)
          let formData = new FormData();
          formData.append("noteId",id)
          // this.nowNotes[index].noteItems.forEach(element => {
          //   formData.append("noteItems",element)
          // });
          formData.append("noteItems",JSON.stringify(this.nowNotes[index].noteItems))
          console.log(formData)
          axios({
                method: 'post',
                url: '/api/Note/endNote',
                data: formData,
                headers: {"Content-Type": "multipart/form-data"},
            }).then((res)=>{
              console.log(res.data)
              this.onRefresh()
              this.onSetLastTime()
              //这个时候必须刷新allnotes
            }).catch(function (error) {console.log(error);}) 
        })
        .catch(() => {
            // on cancel
        });
        //结束待办
      },
      onSetLastTime(){
        let endTime = Date.now().toString()
        store.loverInfo.lastTime = endTime
        axios.get("/api/Info/updateLastTime",{
          params:{
            loverId: store.loverInfo.loverId,
            lastTime: endTime
          }
        }).then((res)=>{
           console.log(res.data)
        }).catch((error)=>{console.log(error)})
      },
      onShare(id){
        axios.get('/api/Note/shareNote', {
              params:{noteId:id}
            }).then((res)=>{
                console,log(res.data)
                this.onRefresh()
                showSuccessToast('分享成功！');}).catch(function (error) {console.log(error);})
        //分享待办
      },
      onShowInput(index){
        this.newNotes[index].isShowInput=!this.newNotes[index].isShowInput
        //v-show变为true
      },
      onShowItem(selector, index){
        if(selector==0){
          this.newNotes[index].isShowItem=!this.newNotes[index].isShowItem
        }else if(selector==1){
          this.nowNotes[index].isShowItem=!this.nowNotes[index].isShowItem
        }else{
          this.hisNotes[index].isShowItem=!this.hisNotes[index].isShowItem
        }
      },
      onUpUnfinished(id,index){
        let count = 0
        this.hisNotes[index].noteItems.forEach(element => {
          count += element.itemState  //如果itemstate都为1，说明都完成了，就没必要重置未完成项了
        });
        if(count>=this.hisNotes[index].noteItems.length){
          showToast("已全部完成")
          return
        }
        axios.get('/api/Note/resetUnfinishNote', {
              params:{noteId:id, loverId:store.loverInfo.loverId}
            }).then((res)=>{
              console.log(res.data)
              this.onRefresh()
              //这个时候必须刷新allnotes
            }).catch(function (error) {console.log(error);}) 
        //结束待办
        //重置为完成的待办
      },
      onDeleteNote(id){
        showConfirmDialog({
          message:
            '确认删除？',
        })
        .then(() => {
          axios.get('/api/Note/deleteNote', {
              params:{
                noteId: id
              }
            }).then((res)=>{
              console.log(res.data)
              this.onRefresh()
            }).catch(function (error) {
                console.log(error);
            }) 
        })
        .catch(() => {
            // on cancel
        });
      },
      arrow(f){
        if(f){
          return this.arrowstyle[0]
        }else{
          return this.arrowstyle[1]
        }
      }
    },
    components: {
  
    }
  }
  </script>

<style>
.n-item .van-checkbox__label{
  line-height: 4vh !important;
}


.n-item .van-cell-group--inset{
  margin:0 0 !important;
  font-size: 2vh;
}

.n-item .van-cell{
  padding-left: 0 !important;
}

.n-noteBottom{
  /* width: 100%; */
  height: 6vh;
  border-bottom-left-radius: 5vw;
  border-bottom-right-radius: 5vw;
  padding:1vh 3vw;
  display: flex;
  align-items: center;
  box-sizing: border-box;
  justify-content: space-between;
  /* border-bottom: 1px solid #62c889; */
}

.n-item{
  /* height: 5vh; */
  line-height: 4vh;
  font-size: 2vh;
  display: flow-root;
  text-align: left;
  padding:0 3vw;
  border-bottom: 1px solid #62c889;
  display: flex;
  align-items: center;

}


.n-noteTop{
  width: 100%;
  height: 5vw;
  border-top-left-radius: 5vw;
  border-top-right-radius: 5vw;
  /* border-bottom: 1px solid #62c889; */

}

.n-newNote{
  width: 94vw;
  margin: 2vw 3vw;
  box-sizing: border-box;
  /* background-color: rgba(98, 200, 137,0.4); */
}

.n-newNote>div{
  background-color: #fff;
}


.n-title{
  font-size: 5vw;
  font-weight: 600;
  line-height: 14vw;
  padding-left: 4vw;
  float: left;
}

.n-addnote{
  float: right;
  margin-right: 4vw;
  padding-top: 4vw;
}

.n-notetitle{
  text-align: left;
  padding: 2vw 2vw;
  font-size: 5vw;
  font-weight: 600;
  
}

.test{
  background-color:#fc4747;
}

.van-dialog__message{
  padding: 2vw !important;
}

.van-dialog{
  width:70vw !important;
}

.slide-fade-enter-active {
    transition: all .2s;
}
.slide-fade-leave-active{
    transition: all .2s;
}
.slide-fade-enter-from, .slide-fade-leave-to
  /* .slide-fade-leave-active for below version 2.1.8 */ {
    /* transform: translateX(10px); */
    transform: translateX(10px);
    opacity: 0;
}
</style>